//
//  YWInsertTextView.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/8/14.
//

#import "YWInsertTextView.h"
#import "YWEditTextImageView.h"

@interface YWInsertTextView ()<UIGestureRecognizerDelegate>

//原始view
@property(nonatomic,strong)UIImageView *bgImageView;

/** 要绘制的图片 */
@property (nonatomic, strong) UIImage * ogrinalImage;

@property(nonatomic,strong)NSMutableArray *imageViewArray; //数组装图片、图片里有属性

@property(nonatomic,weak)YWEditTextImageView *edittingImageView; //正在编辑的图片


@end

@implementation YWInsertTextView

-(NSMutableArray *)imageViewArray{
    if(_imageViewArray == nil){
        _imageViewArray = [NSMutableArray array];
    }
    return _imageViewArray;
}

-(UIImageView *)bgImageView{
    if(_bgImageView == nil){
        UIImageView *bgImageView = [[UIImageView alloc] init];
        _bgImageView = bgImageView;
    }
    return _bgImageView;
}

//纯代码用这个
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

//xib用这个
-(void)awakeFromNib{
    [super awakeFromNib];
    [self setup];
    
}

//初始化
-(void)setup{
    [self addSubview:self.bgImageView];
    self.clipsToBounds = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTap)];
    [self addGestureRecognizer:tap];
}


-(void)layoutSubviews{
    [super layoutSubviews];
    
    self.bgImageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}



//设置初始图片
- (void)setFirstImage:(UIImage *)image{
    
    _ogrinalImage = image;
    
    self.bgImageView.image = image;
}

//设置表情图片
-(void)createImageViewWithTextStatus:(YWTextStatus *)textStatus{
    
    YWEditTextImageView *imageV = [[YWEditTextImageView alloc] init];
//    imageV.backgroundColor = [UIColor lightGrayColor];
//    imageV.frame = self.bounds;
    imageV.size = textStatus.image.size;
    imageV.center = CGPointMake(self.width*1.0/2, self.height*1.0/2);
    
    imageV.userInteractionEnabled = YES;
    imageV.textStatus = textStatus;
    imageV.image = textStatus.image;
    imageV.contentMode = UIViewContentModeScaleAspectFit;
    
    [self addSubview:imageV];
    [self.imageViewArray addObject:imageV];
    [imageV addObserver:self forKeyPath:@"textStatus.isEdit" options:NSKeyValueObservingOptionNew context:NULL];
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [imageV addGestureRecognizer:tap];
    
    
    // pan
    // 拖拽手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]
                                   initWithTarget:self action:@selector(pan:)];
    
    [imageV addGestureRecognizer:pan];
    
    // pinch
    // 捏合
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    
    pinch.delegate = self;
    [imageV addGestureRecognizer:pinch];
    
    
    //添加旋转
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
    rotation.delegate = self;
    
    [imageV addGestureRecognizer:rotation];
    
}

-(void)reEditImageViewWithTextStatus:(YWTextStatus *)textStatus{
    
    //这里要判断textStatus的text是否空或者长度是0、从而决定删除还是修改文字
    //进入可编辑的一般都是self.edittingImageView指着的
    if([self.edittingImageView.textStatus.tag isEqualToString:textStatus.tag]){
        
        if(textStatus.text == nil || textStatus.text.length == 0){
            [self removeImageView:self.edittingImageView];
        }
        else{
            
            
            self.edittingImageView.transform = CGAffineTransformIdentity;
            
            self.edittingImageView.size = textStatus.image.size;
            self.edittingImageView.center = CGPointMake(self.width*1.0/2, self.height*1.0/2);
            self.edittingImageView.textStatus = textStatus;
            self.edittingImageView.image = textStatus.image;
            
            
//            self.edittingImageView.centerX = self.edittingImageView.centerX + textStatus.incrementCenterX;
//            self.edittingImageView.centerY = self.edittingImageView.centerY + textStatus.incrementCenterY;
            
            self.edittingImageView.transform = CGAffineTransformMakeScale(textStatus.scale, textStatus.scale);
            
//            self.edittingImageView.transform = CGAffineTransformScale(self.edittingImageView.transform, textStatus.scale, textStatus.scale);
            self.edittingImageView.transform = CGAffineTransformRotate(self.edittingImageView.transform, textStatus.rotation);
            self.edittingImageView.transform = CGAffineTransformTranslate(self.edittingImageView.transform, textStatus.transX, textStatus.transY);
            
            NSLog(@"---");
        }
        
        
    }
    
    
    
}

-(void)removeImageView:(YWEditTextImageView *)imageView{
    [imageView removeObserver:self forKeyPath:@"textStatus.isEdit"];
    [self.imageViewArray removeObject:imageView];
    [imageView removeFromSuperview];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    //监听播放状态做出的响应
    if ([keyPath isEqualToString:@"textStatus.isEdit"]) {
        
        // 改变的相关值
        NSLog(@"%@",change);
        
        BOOL isEdit = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
        
        if([object isKindOfClass:[YWEditTextImageView class]]){
            
            if(isEdit == YES){
                
                self.edittingImageView.layer.borderWidth = 0;
                
                YWEditTextImageView *imageView = (YWEditTextImageView *)object;
                
                imageView.layer.borderWidth = 1;
                imageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
                
                [self bringSubviewToFront:imageView];
                
            }
            else{
                
                YWEditTextImageView *imageView = (YWEditTextImageView *)object;
                imageView.layer.borderWidth = 0;
                
            }
            
        }
        
    }
    
    
    
    
    
    
}

-(void)resetIsEdit{
    
    self.edittingImageView.textStatus.isEdit = NO;
}

-(void)viewTap{
    
    self.edittingImageView.textStatus.isEdit = NO;
}

//单击的时候调用
-(void)tap:(UITapGestureRecognizer *)tap{
    YWEditTextImageView *imageView = (YWEditTextImageView *)tap.view;
    
    if(imageView.textStatus.isEdit == YES){
        //这里就去编辑
        if ([self.delegate respondsToSelector:@selector(insertTextView:changeTextWithStatus:)]) {
            [self.delegate insertTextView:self changeTextWithStatus:imageView.textStatus];
        }
        
    }
    else{
        
        //换一个imageView进入可编辑状态
        self.edittingImageView.textStatus.isEdit = NO;
        imageView.textStatus.isEdit = YES;
        self.edittingImageView = imageView;
    }
    
    
    
}

//捏合的时候调用.
- (void)pinch:(UIPinchGestureRecognizer *)pinch
{
    
    pinch.view.transform = CGAffineTransformScale( pinch.view.transform, pinch.scale, pinch.scale);
    
    
    YWEditTextImageView *imageView = (YWEditTextImageView *)pinch.view;
    imageView.textStatus.scale = pinch.scale * imageView.textStatus.scale;
    
    
    
    
    
    // 复位
    pinch.scale = 1;
    
    
}


//旋转的时候调用
- (void)rotation:(UIRotationGestureRecognizer *)rotation
{
    // 旋转图片
    rotation.view.transform = CGAffineTransformRotate(rotation.view.transform, rotation.rotation);
    
    YWEditTextImageView *imageView = (YWEditTextImageView *)rotation.view;
    imageView.textStatus.rotation = rotation.rotation + imageView.textStatus.rotation;
    
    // 复位,只要想相对于上一次旋转就复位
    rotation.rotation = 0;
    
    
}


//拖动的时候调用
- (void)pan:(UIPanGestureRecognizer *)pan{
    
    CGPoint transP = [pan translationInView:pan.view];
    
    pan.view.transform = CGAffineTransformTranslate(pan.view.transform, transP.x, transP.y);
    
//    pan.view.centerX = pan.view.centerX + transP.x;
//    pan.view.centerY = pan.view.centerY + transP.y;
//    NSLog(@"))))))-----%f",pan.view.centerX);
    

    YWEditTextImageView *imageView = (YWEditTextImageView *)pan.view;
    imageView.textStatus.transX = transP.x + imageView.textStatus.transX;
    imageView.textStatus.transY = transP.y + imageView.textStatus.transY;
    
    
    //复位
    [pan setTranslation:CGPointZero inView:pan.view];
    
}


//能够同时支持多个手势
-(BOOL)gestureRecognizer:(nonnull UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(nonnull UIGestureRecognizer *)otherGestureRecognizer{
    
    return YES;
}


//获取当前图层
-(UIImage *)getCurrentLayer{
    
    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
    
    //2.把画板上的内容渲染到上下文当中
    CGContextRef ctx =  UIGraphicsGetCurrentContext();
    [self.layer renderInContext:ctx];
    
    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}


@end
